<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>登录/注册 - 酒店管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>

<body class="bg-gray-100 flex items-center justify-center min-h-screen p-4">

<div class="w-full max-w-md bg-white p-8 rounded-lg shadow-md">
    <h2 class="text-2xl font-bold mb-6 text-center">酒店管理系统</h2>

    <!-- 类型选择 -->
    <div class="flex justify-center mb-6 space-x-4">
        <button id="loginBtn" class="auth-type-btn px-6 py-2 bg-blue-500 text-white rounded-lg">登录</button>
        <button id="registerBtn" class="auth-type-btn px-6 py-2 bg-green-500 text-white rounded-lg">注册</button>
        <button id="backToIndexBtn" class="px-6 py-2 bg-gray-500 text-white rounded-lg">返回首页</button>
    </div>

    <!-- 内容容器 -->
    <div id="authContent" class="space-y-6"></div>
</div>

<script>
    // 返回首页按钮事件
    document.getElementById('backToIndexBtn').addEventListener('click', () => {
        window.location.href = 'index.html';
    });

    // 切换到登录界面
    function showLogin() {
        const content = document.getElementById('authContent');
        content.innerHTML = `
            <h3 class="text-xl font-semibold mb-4 text-center">请选择登录类型</h3>
            <div class="space-y-4">
                <button class="auth-action-btn w-full text-left p-4 border rounded-lg hover:bg-gray-50 flex items-center" data-type="user-login">
                    <i class="fas fa-user mr-3 text-blue-500 text-xl"></i>
                    <span>用户登录</span>
                </button>
                <button class="auth-action-btn w-full text-left p-4 border rounded-lg hover:bg-gray-50 flex items-center" data-type="merchant-login">
                    <i class="fas fa-store mr-3 text-green-500 text-xl"></i>
                    <span>商家登录</span>
                </button>
                <button class="auth-action-btn w-full text-left p-4 border rounded-lg hover:bg-gray-50 flex items-center" data-type="admin-login">
                    <i class="fas fa-shield-alt mr-3 text-purple-500 text-xl"></i>
                    <span>管理员登录</span>
                </button>
            </div>
        `;

        addAuthActionListeners();
    }

    // 切换到注册界面
    function showRegister() {
        const content = document.getElementById('authContent');
        content.innerHTML = `
            <h3 class="text-xl font-semibold mb-4 text-center">请选择注册类型</h3>
            <div class="space-y-4">
                <button class="auth-action-btn w-full text-left p-4 border rounded-lg hover:bg-gray-50 flex items-center" data-type="user-register">
                    <i class="fas fa-user-plus mr-3 text-blue-500 text-xl"></i>
                    <span>用户注册</span>
                </button>
                <button class="auth-action-btn w-full text-left p-4 border rounded-lg hover:bg-gray-50 flex items-center" data-type="merchant-register">
                    <i class="fas fa-store mr-3 text-green-500 text-xl"></i>
                    <span>商家注册</span>
                </button>
                <button class="auth-action-btn w-full text-left p-4 border rounded-lg hover:bg-gray-50 flex items-center" data-type="admin-register">
                    <i class="fas fa-shield-alt mr-3 text-purple-500 text-xl"></i>
                    <span>管理员注册</span>
                </button>
            </div>
        `;

        addAuthActionListeners();
    }

    // 添加认证操作监听器
    function addAuthActionListeners() {
        document.querySelectorAll('.auth-action-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const type = e.target.dataset.type || e.target.closest('button').dataset.type;
                showAuthForm(type);
            });
        });
    }

    // 显示具体的表单
    function showAuthForm(type) {
        const content = document.getElementById('authContent');
        let formTitle = '';
        let formFields = '';
        let submitButtonText = '';
        let backText = '';

        switch (type) {
            case 'user-login':
                formTitle = '用户登录';
                formFields = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="username" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="password" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                    </div>
                `;
                submitButtonText = '登录';
                backText = '返回登录类型选择';
                break;

            case 'merchant-login':
                formTitle = '商家登录';
                formFields = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商家名称</label>
                            <input type="text" id="merchantName" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="merchantPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                    </div>
                `;
                submitButtonText = '登录';
                backText = '返回登录类型选择';
                break;

            case 'admin-login':
                formTitle = '管理员登录';
                formFields = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">管理员名称</label>
                            <input type="text" id="adminName" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="adminPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500" required>
                        </div>
                    </div>
                `;
                submitButtonText = '登录';
                backText = '返回登录类型选择';
                break;

            case 'user-register':
                formTitle = '用户注册';
                formFields = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="newUsername" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="newPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                            <input type="password" id="confirmPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">性别</label>
                            <select id="gender" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">生日</label>
                            <input type="date" id="birthday" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                    </div>
                `;
                submitButtonText = '注册';
                backText = '返回注册类型选择';
                break;

            case 'merchant-register':
                formTitle = '商家注册';
                formFields = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商家名称</label>
                            <input type="text" id="newMerchantName" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="newMerchantPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                            <input type="password" id="confirmMerchantPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">地址</label>
                            <input type="text" id="address" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">成立年份</label>
                            <input type="number" id="establishmentYear" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">联系信息</label>
                            <input type="text" id="contactInfo" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">关键词</label>
                            <input type="text" id="keywords" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" required>
                        </div>
                    </div>
                `;
                submitButtonText = '注册';
                backText = '返回注册类型选择';
                break;

            case 'admin-register':
                formTitle = '管理员注册';
                formFields = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">管理员名称</label>
                            <input type="text" id="newAdminName" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500" required>
                            <small class="text-gray-500">用户名需为 3~20 位字母数字</small>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="newAdminPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500" required>
                            <small class="text-gray-500">密码需至少 8 位，包含字母、数字、特殊字符@#$%^&+=</small>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                            <input type="password" id="confirmAdminPassword" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500" required>
                        </div>
                    </div>
                `;
                submitButtonText = '注册';
                backText = '返回注册类型选择';
                break;
        }

        content.innerHTML = `
            <h3 class="text-xl font-semibold mb-4 text-center">${formTitle}</h3>
            ${formFields}
            <div class="pt-4">
                <button id="submitAuthForm" class="w-full py-2 px-4 ${
                    type.endsWith('-login') ? 'bg-blue-500' : 'bg-green-500'
                } text-white rounded-lg hover:${
                    type.endsWith('-login') ? 'bg-blue-600' : 'bg-green-600'
                } transition duration-200">
                    ${submitButtonText}
                </button>
                <button id="backToTypeSelection" class="mt-2 w-full text-center py-2 text-sm text-gray-600 hover:text-gray-900">
                    ← ${backText}
                </button>
            </div>
        `;

        // 添加提交事件监听器
        document.getElementById('submitAuthForm').addEventListener('click', () => {
            handleAuthSubmit(type);
        });

        // 添加返回事件监听器
        document.getElementById('backToTypeSelection').addEventListener('click', () => {
            if (type.includes('login')) {
                showLogin();
            } else {
                showRegister();
            }
        });
    }

    function basicValidateInput(type) {
        let isValid = true;

        switch (type) {
            case 'user-login':
            case 'merchant-login':
            case 'admin-login':
                const nameField = document.getElementById(type.includes('user') ? 'username' :
                    type.includes('merchant') ? 'merchantName' : 'adminName');
                const passwordField = document.getElementById(type.includes('user') ?
                    'password' : type.includes('merchant') ?
                    'merchantPassword' : 'adminPassword');

                if (!nameField.value.trim()) {
                    alert('请输入用户名/商家名称/管理员名称');
                    isValid = false;
                }

                if (!passwordField.value.trim()) {
                    alert('请输入密码');
                    isValid = false;
                }
                break;

            case 'user-register':
                const newUser = document.getElementById('newUsername').value.trim();
                const newPassword = document.getElementById('newPassword').value;
                const confirmPassword = document.getElementById('confirmPassword').value;

                if (!newUser) {
                    alert('请输入用户名');
                    isValid = false;
                }

                if (!newPassword || !confirmPassword) {
                    alert('请输入密码和确认密码');
                    isValid = false;
                }
                break;

            case 'merchant-register':
                const newMerchant = document.getElementById('newMerchantName').value.trim();
                const newMerchantPassword = document.getElementById('newMerchantPassword').value;
                const confirmMerchantPassword = document.getElementById('confirmMerchantPassword').value;
                const address = document.getElementById('address').value.trim();
                const establishmentYear = document.getElementById('establishmentYear').value.trim();
                const contactInfo = document.getElementById('contactInfo').value.trim();
                const keywords = document.getElementById('keywords').value.trim();

                if (!newMerchant) {
                    alert('请输入商家名称');
                    isValid = false;
                }

                if (!newMerchantPassword || !confirmMerchantPassword) {
                    alert('请输入密码和确认密码');
                    isValid = false;
                }

                if (!address) {
                    alert('请输入地址');
                    isValid = false;
                }

                if (!establishmentYear) {
                    alert('请输入成立年份');
                    isValid = false;
                }

                if (!contactInfo) {
                    alert('请输入联系信息');
                    isValid = false;
                }

                if (!keywords) {
                    alert('请输入关键词');
                    isValid = false;
                }
                break;

            case 'admin-register':
                const newAdmin = document.getElementById('newAdminName').value.trim();
                const newAdminPassword = document.getElementById('newAdminPassword').value;
                const confirmAdminPassword = document.getElementById('confirmAdminPassword').value;

                if (!newAdmin) {
                    alert('请输入管理员名称');
                    isValid = false;
                }

                if (!newAdminPassword || !confirmAdminPassword) {
                    alert('请输入密码和确认密码');
                    isValid = false;
                }
                break;
        }

        return isValid;
    }

    async function handleAuthSubmit(type) {
        // 只做轻量级字段非空检查
        if (!basicValidateInput(type)) {
            return;
        }

        let endpoint = '';
        let data = {};

        switch (type) {
            case 'user-login':
                endpoint = '/user/login';
                data = {
                    username: document.getElementById('username').value,
                    password: document.getElementById('password').value
                };
                break;

            case 'merchant-login':
                endpoint = '/merchant/login';
                data = {
                    merchantName: document.getElementById('merchantName').value,
                    password: document.getElementById('merchantPassword').value
                };
                break;

            case 'admin-login':
                endpoint = '/admin/login';
                data = {
                    adminName: document.getElementById('adminName').value,
                    password: document.getElementById('adminPassword').value
                };
                break;

            case 'user-register':
                endpoint = '/user/register';
                data = {
                    username: document.getElementById('newUsername').value,
                    password: document.getElementById('newPassword').value,
                    confirmPassword: document.getElementById('confirmPassword').value,
                    gender: document.getElementById('gender').value,
                    birthday: document.getElementById('birthday').value
                };
                break;

            case 'merchant-register':
                endpoint = '/merchant/register';
                data = {
                    merchantName: document.getElementById('newMerchantName').value,
                    password: document.getElementById('newMerchantPassword').value,
                    confirmPassword: document.getElementById('confirmMerchantPassword').value,
                    address: document.getElementById('address').value,
                    establishmentYear: document.getElementById('establishmentYear').value,
                    contactInfo: document.getElementById('contactInfo').value,
                    keywords: document.getElementById('keywords').value
                };
                break;

            case 'admin-register':
                endpoint = '/admin/register';
                data = {
                    adminName: document.getElementById('newAdminName').value,
                    password: document.getElementById('newAdminPassword').value,
                    confirmPassword: document.getElementById('confirmAdminPassword').value
                };
                break;
        }

        try {
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams(data).toString()
            });

            const resultText = await response.text();
            let result;

            try {
                result = JSON.parse(resultText);
            } catch (e) {
                console.error('JSON 解析失败:', resultText);
                alert('服务器返回非 JSON 数据，请重试');
                return;
            }

            if (!response.ok) {
                const errorMessage = result.message || '注册失败，请检查输入或稍后再试';
                alert(errorMessage);
                return;
            }

            if (result.success) {
                switch (type) {
                    case 'user-register':
                        alert('注册成功！即将跳转到登录页');
                        showLogin(); // 跳转回登录页
                        return;
                    case 'merchant-register':
                        alert('商家注册成功，正在等待管理员审核，即将跳转到登录页');
                        showLogin();
                        return;
                    case 'admin-register':
                        alert('管理员注册成功！即将跳转到登录页');
                        showLogin();
                        return;
                    case 'user-login':
                        // 将用户名作为参数添加到跳转的 URL 中
                        window.location.href = `user-dashboard.html?username=${encodeURIComponent(data.username)}`;
                        return;

                    case 'merchant-login':
                        // 将商家名称作为参数添加到跳转的 URL 中
                        window.location.href = `merchant-dashboard.html?merchantName=${encodeURIComponent(data.merchantName)}`;
                        return;

                    case 'admin-login':
                        window.location.href = 'admin-dashboard.html';
                        return;
                }
            } else {
                switch (type) {
                    case 'user-login':
                        if (result.userStatus === '黑户') {
                            if (confirm('您已被管理员封号，是否向管理员提交解封申请？')) {
                                await submitUnblockRequest(data.username);
                            }
                        } else if (result.userStatus === '解封中') {
                            alert('管理员正在审核中');
                        } else {
                            alert(result.message || '用户名或密码错误');
                        }
                        break;

                    case 'merchant-login':
                        if (result.applicationStatus === '未通过') {
                            alert('您的申请未通过审核，请联系管理员');
                        } else if (result.applicationStatus === '申请中') {
                            alert('您的账号仍在审核中，请耐心等待');
                        } else {
                            alert(result.message || '商家名称或密码错误');
                        }
                        break;

                    case 'admin-login':
                        alert(result.message || '管理员名称或密码错误');
                        break;

                    default:
                        alert(result.message || '登录失败，请重试');
                        break;
                }
            }
        } catch (error) {
            console.error('网络请求错误:', error);
            alert('发生网络错误，请重试');
        }
    }

    async function submitUnblockRequest(username) {
        try {
            const response = await fetch('/user/submitUnblockRequest', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({ username: username }).toString()
            });

            if (!response.ok) {
                const errorData = await response.json();
                alert(errorData.message || '提交解封申请失败，请重试');
            } else {
                const result = await response.json();
                alert(result.message || '提交解封申请成功');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('发生网络错误，请重试');
        }
    }

    // 初始化页面
    function init() {
        // 默认显示登录界面
        showLogin();

        // 绑定类型选择事件
        document.getElementById('loginBtn').addEventListener('click', showLogin);
        document.getElementById('registerBtn').addEventListener('click', showRegister);
    }

    // 页面加载时初始化
    window.onload = init;
</script>

</body>

</html>